<?php

// Authorized Pages for each user type
$tab_pages[""] = array("login");
$tab_pages["annonyme"] = array("login");
$tab_pages["user_support"] = array(
    'home',
    'validator',
    'logout',
    'user_admin',
    'login',
    'about_us',
    'parameter'
);
// Default page for each user type
$tab_pages["user_support"]["main_link"] = APPLICATION_URL . "/home/list";

function is_utilisateur_connecte() {
	return isset($_SESSION['userID']) && $_SESSION['userID'];
}

// Check if user is correctly connected
if (!is_utilisateur_connecte()) {
	if (!is_page_courante('login') && !is_page_courante('index') && !is_page_courante('lost_password'))
	{
		if ( isset($_GET['FUNC']) && isset($_GET['VAL_NUM']) )
		{
			$_SESSION['url_demande'] = '';
			echo  "ajax_timeout";
			die();
		}
		else {
			$_SESSION['url_demande'] = '';
			redirect(APPLICATION_URL . '/login/login/?return_link='. urlencode($_SERVER['REQUEST_URI']));
		}

	}
	elseif (is_page_courante('index.php')) {
		$_SESSION['url_demande'] = '';
		redirect(APPLICATION_URL . '/login/login/?return_link='. urlencode($_SERVER['REQUEST_URI']));
	}
	elseif (!isset($_SESSION['url_demande'])) {
		$_SESSION['url_demande'] = '';
	}
}

// User directly requested login.php
elseif (is_page_courante('/login/login.php')) {
	$_SESSION['url_demande'] = '';
}

if (!isset($_SESSION["userClasse"]))
	$_SESSION["userClasse"]='annonyme';

$smarty = DRX::load("smarty");
$smarty->assign("user_classe", $_SESSION["userClasse"]);
$smarty->assign('is_utilisateur_connecte', is_utilisateur_connecte());

if (!isset($_SESSION["userID"]))
	$_SESSION["userID"] = 0;

$smarty->assign("user_id", $_SESSION["userID"]);

if(isset($g_user) && !$g_user->isAllowedAccessProject())
{
	die("Access is forbidden!");
}
// check whether or not current account was DISABLED or DELETED from LOGIN table
else if($_SESSION["userID"] != "" )
{
	 $login = new Login();

	 if(!$login->isExistLoginID())
	 {
		// free all SESSION variables
		session_unset();
		// redirect to login page
	 	redirect(APPLICATION_URL . '/login/login/?return_link='. urlencode($_SERVER['REQUEST_URI']));
	 }
}

// Check authorizations
$controller = DRX::load("controller");
if (isset($controller)) {
	if (!in_array($controller, $tab_pages[$_SESSION["userClasse"]])) {
		redirect($tab_pages[$_SESSION["userClasse"]]["main_link"]);
	}
	$smarty->assign("section", $controller);
}
else {
	die("La variable section n'est pas encore definie");
}